from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from exams.models import Exam, Question, User, TakenExam
import datetime
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from helper import user_is_teacher, int_format

@login_required
def index(request):

	if user_is_teacher(request):
		return teacher(request)
	
	exam_list = Exam.objects.all()
	takenexam_list = TakenExam.objects.filter(student=request.user)
        avg_grade = 0
	for takenexam in takenexam_list:
		exam_list = exam_list.exclude(id=takenexam.exam.id)
		avg_grade = avg_grade + takenexam.grade
	exam_list = exam_list.filter(deadline__gte=datetime.datetime.today())

	te_len = len(takenexam_list)
	if te_len == 0:
		te_len = 1
	avg_grade = avg_grade / te_len
	return render_to_response('exams/index.html', {'exam_list': exam_list, 
							'takenexam_list': takenexam_list,
							'user' : request.user, 
							'avg_grade' : avg_grade})

@login_required
def teacher(request):

	if not user_is_teacher(request):
		return index(request)
	
	exam_list = Exam.objects.filter(deadline__gte=datetime.datetime.today())
	finished_list = Exam.objects.filter(deadline__lt=datetime.datetime.today())
	return render_to_response('exams/index_teacher.html', {'exam_list': exam_list,
											'finished_list': finished_list,
											'user' : request.user})

@login_required
def submit(request, exam_id):
	exam = get_object_or_404(Exam, pk=exam_id)

	for question in exam.question_set.all():
		try:		
			request.POST['question_' + str(question.id)]
		except:
			
			return render_to_response('exams/show.html', {'exam': exam,
											'error_message': "You didn't select all choices.", 
											}, context_instance=RequestContext(request))
	
	total_questions =  exam.question_set.count()
	# save guard for divbyzero, but exam should not have have zero questions
	if total_questions == 0:
		return render_to_response('exams/show.html', {'exam': exam,
											'error_message': "Exam has no questions.", 
											}, context_instance=RequestContext(request))
	total_correct_value = 0
        total_value = 0

	for question in exam.question_set.all():
                total_value += question.value
		answer = question.answer_set.get(pk=request.POST['question_' + str(question.id)])
		if answer.is_correct:
			total_correct_value += question.value
	if(total_value == 0):
		total_value = 1  #no div by zero pleas
	grade = float((float(total_correct_value)/float(total_value)) * 10)
	#print str(grade * 10) + "% correct"
	
	user = request.user
	te = TakenExam(
		exam = exam,
		student = user,
		dateTaken = datetime.datetime.now(),
		grade = float(grade))
	try:
		te.save()
	except IntegrityError:
		return render_to_response('exams/show.html', {'exam': exam,
											'error_message': "You have already taken this exam.", 
											}, context_instance=RequestContext(request))
	
        return HttpResponseRedirect(reverse('exam_result', args=(te.id,)))	

@login_required
def new(request):

	if not user_is_teacher(request):
		return index(request)

	exam = Exam()
	exam.name = ""
	exam.date_created = datetime.datetime.now() 
	exam.deadline = datetime.datetime.now() + datetime.timedelta(days=7)
	return render_to_response('exams/new.html', {'exam': exam }, 
									context_instance=RequestContext(request))
@login_required	
def create(request):
	
	if not user_is_teacher(request):
		return index(request)

	exam = Exam()
	exam.name = request.POST['exam_name']	
	exam.date_created = datetime.datetime.now()
	exam.deadline = request.POST['exam_deadline']	
	exam.save()	

	q_count = 1
	#find posted questions
	while(True):
		que_post = 'question_' + str(q_count)
		if que_post in request.POST:
			web_question = request.POST[que_post]
                        question_value = request.POST['val_' + que_post]
			#print "question: " +  web_question
			question = exam.question_set.create(text=web_question, number=q_count, value=question_value)
			a_count = 1
			#find posted answers
			while(True):
				ans_post = 'answer_' + str(q_count) + '_' + str(a_count)
				if ans_post in request.POST:
					print "is in response"
	 				web_answer = request.POST[ans_post]

					#check if answer is correct
					correct = False
					chk_post = 'answer_ck_' + str(q_count) + '_' + str(a_count)
					if chk_post in request.POST:
						correct = True

					question.answer_set.create(text=web_answer, number=0, is_correct=correct)
				else:
					break
				a_count += 1
		else:
			break
		q_count += 1

	exam.save()

	return HttpResponseRedirect(reverse('exams.views.index'))


@login_required
def delete(request, exam_id):

	if not user_is_teacher(request):
		return index(request)

	exam = get_object_or_404(Exam, pk=exam_id)

	for question in exam.question_set.all():
		for answer in question.answer_set.all():
			answer.delete()
		question.delete()

	exam.delete()

	return HttpResponseRedirect(reverse('exams.views.index'))

@login_required
def summary(request, exam_id):
    if not user_is_teacher(request):
        return index(request)
    ex = get_object_or_404(Exam, pk=exam_id)
    takenexam_list = TakenExam.objects.filter(exam=ex)
    return render_to_response('exams/result_teacher.html', {'takenexam_list': takenexam_list}, context_instance=RequestContext(request))

